package cn.chenxinjie.hrm.userdetails;

import cn.chenxinjie.hrm.domain.LoginUser;
import cn.chenxinjie.hrm.domain.Permission;
import cn.chenxinjie.hrm.feign.UserInfoFeign;
import cn.chenxinjie.hrm.mapper.LoginUserMapper;
import cn.chenxinjie.hrm.mapper.PermissionMapper;
import cn.chenxinjie.hrm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈鑫杰
 * @date 2022/3/21 15:50
 */
@Service
public class HrmUserDetailsService implements UserDetailsService {

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UserInfoFeign userInfoFeign;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 基于用户名查询数据库   (认证)
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        LoginUser one = loginUserMapper.selectOne(loginUser);
        Assert.notNull(one,"查无此人");

        // 查询当前登陆用户所拥有的权限   (授权)
        List<Permission> list = permissionMapper.findRolePermissionsById(one.getId());
        List<SimpleGrantedAuthority> permissions = new ArrayList<>();
        list.stream().forEach(e -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(e.getSn());
            permissions.add(authority);
        });

        AjaxResult result = userInfoFeign.getTenantInfoById(one.getId());
        Assert.isTrue(result.isSuccess(),"G啦");
        Object resultObj = result.getResultObj();

        redisTemplate.opsForValue().set("authen::" + one.getUsername(), resultObj);

        User user = new User(one.getUsername(), one.getPassword(), permissions);
        return user;
    }
}
